//
//  DynamicCollectionView.m
//  DymanicCollectionView
//
//  Created by LeeBruce on 16/11/14.
//  Copyright © 2016年 LeeBruce. All rights reserved.
//

//#define Main_interface @"http://220.249.50.163/sendbydriver/"
//
//#define  application_json @"application/json"
//#define STR_F2(p1, p2)     [NSString stringWithFormat:@"%@%@", p1, p2]
//
//#define qiniu_token  STR_F2(Main_interface,@"qiniu/upload/ticket")



#import "DynamicCollectionView.h"
#import "DynamicCollectionViewCell.h"
#import "QiniuSDK.h"
#import "Common.h"
#import "WKProgressHUD.h"

@interface DynamicCollectionView ()<UICollectionViewDelegate,UICollectionViewDataSource,UIImagePickerControllerDelegate,UINavigationControllerDelegate,UICollectionViewDelegateFlowLayout>

@property (nonatomic,strong) UICollectionView *collectionView;

@property (nonatomic,strong) NSMutableArray *imgArray;
@property (nonatomic,strong) NSMutableArray *imageArray;
@property (nonatomic,copy) NSString *token;

@property (nonatomic,strong) WKProgressHUD *hud;



@property (nonatomic,strong) NSIndexPath *currentIndexPath;
@end


@implementation DynamicCollectionView

-(instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        
        self.imgArray = [NSMutableArray array];
        self.imageArray = [NSMutableArray array];
        _currentIndexPath = [NSIndexPath indexPathForRow:0 inSection:0];
        [self initCollectionView];
        
    }
    
    
    return self;
}

-(void )initCollectionView
{
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
        layout.itemSize = CGSizeMake(80 * kHeight, 80 * kHeight);
    layout.sectionInset = UIEdgeInsetsMake(10, 20, 10, 20);
        
        UICollectionView *collectionView = [[UICollectionView alloc]initWithFrame:self.bounds collectionViewLayout:layout];
        collectionView.delegate = self;
        collectionView.dataSource = self;
    
    collectionView.backgroundColor = WhiteColor;
        
        [collectionView registerClass:[DynamicCollectionViewCell class] forCellWithReuseIdentifier:@"DynamicCollectionViewCell"];

        
        _collectionView = collectionView;
        
        [self addSubview:_collectionView];
    
}



#pragma mark UICollectionViewDataSource
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.imgArray.count + 1 ;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{

    DynamicCollectionViewCell *cell = (DynamicCollectionViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:@"DynamicCollectionViewCell" forIndexPath:indexPath];
    
    if (indexPath.row  == _imgArray.count) {
        cell.imageView.image = [UIImage imageNamed:@"car_add"];
    } else {
        cell.imageView.image = self.imageArray[indexPath.row];
    }
    

    return cell;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    _currentIndexPath = indexPath;
        
    [self photoButton];
   
    
}


#pragma mark 获取照片
-(void)photoButton
{
    __weak typeof(self) weakSelf = self;
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        
        [weakSelf getPictureFromCamera];
        
    }];
//    UIAlertAction *action3 = [UIAlertAction actionWithTitle:@"从相册选取" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//        
//        [weakSelf getPictureFromLibrary];
//        
//    }];
//    
    UIAlertAction *action4 = [UIAlertAction actionWithTitle:@"删除" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
       
        [weakSelf deletePicture];
        
    }];
    
    [alert addAction:action1];
    [alert addAction:action2];
    //[alert addAction:action3];
    if (_currentIndexPath.row != self.imgArray.count ){
        
        [alert addAction:action4];
        
    }
    
    
    [[self viewController] presentViewController:alert animated:YES completion:nil];
    
}

#pragma mark 拍照
-(void)getPictureFromCamera
{
    UIImagePickerController *picker = [[UIImagePickerController alloc]init];
    picker.delegate = self;
    picker.allowsEditing = YES;
    picker.sourceType = UIImagePickerControllerSourceTypeCamera;
    
    [[self viewController] presentViewController:picker animated:YES completion:nil];
}

#pragma mark 从相册选取
-(void)getPictureFromLibrary
{
    UIImagePickerController *picker = [[UIImagePickerController alloc]init];
    picker.delegate = self;
    picker.allowsEditing = YES;
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    
    [[self viewController] presentViewController:picker animated:YES completion:nil];
    
}

#pragma mark 删除
-(void)deletePicture
{
    
    [self.imgArray removeObjectAtIndex:_currentIndexPath.row];
    [self.imageArray removeObjectAtIndex:_currentIndexPath.row];
    
    [self.collectionView reloadData];
    
}


#pragma mark UIImagePickerControllerDelegate
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    [picker dismissViewControllerAnimated:YES completion:^{
        
        UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
        
        DynamicCollectionViewCell *cell = (DynamicCollectionViewCell *)[_collectionView cellForItemAtIndexPath:_currentIndexPath];
        cell.imageView.image = image;
        
        if (_currentIndexPath.row  != _imgArray.count) {
            
            [self.imageArray replaceObjectAtIndex:_currentIndexPath.row withObject:image];
            
        } else {
            [self.imageArray addObject:image];
        }
        
        self.hud  = [WKProgressHUD showInView:self withText:@"" animated:YES];

        //上传服务器
        [self getTokenFromQN];
        
    }];
}


- (UIViewController *)viewController {
    for (UIView* next = [self superview]; next; next = next.superview) {
        UIResponder *nextResponder = [next nextResponder];
        if ([nextResponder isKindOfClass:[UIViewController class]]) {
            return (UIViewController *)nextResponder;
        }
    }
    return nil;
}

#pragma mark 上传七牛
-(NSData *)getImageWith:(UIImage *)image
{
    NSData *data = nil;
    if (UIImagePNGRepresentation(image)) {
        
        data = UIImageJPEGRepresentation(image, 0.1);
        
        
    } else {
        data = UIImagePNGRepresentation(image);
        
        
    }
    
    return data;
}

#pragma mark 从七牛获取Token
-(void)getTokenFromQN
{
    
    [Common requestWithUrlString:qiniu_token contentType:application_json errorShow:YES  finished:^(id responseObj) {
        if ([responseObj[@"success"] boolValue]) {
            
            self.token = responseObj[@"data"];
            
            DynamicCollectionViewCell *cell = (DynamicCollectionViewCell *)[_collectionView cellForItemAtIndexPath:_currentIndexPath];
            
                [self uploadImageToQNWithData:[self getImageWith:cell.imageView.image]];
                
            
        }
    } failed:^(NSString *errorMsg) {
        
        
        NSLog(@"%@",errorMsg);
    }];
    
    
    
}

-(void)uploadImageToQNWithData:(NSData *)data
{
    
    QNUploadManager *upManager = [[QNUploadManager alloc]init];
    
    QNUploadOption *uploadOption = [[QNUploadOption alloc]initWithMime:nil progressHandler:^(NSString *key, float percent) {
        
    } params:nil checkCrc:NO cancellationSignal:nil];
    
    [upManager putData:data key:nil token:self.token complete:^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
        

        if (_currentIndexPath.row  !=  _imgArray.count ) {
            //替换
            [self.imgArray replaceObjectAtIndex:_currentIndexPath.row withObject:resp[@"key"]];
            
            } else {
            //添加
            [self.imgArray addObject:resp[@"key"]];
                        
            }

        dispatch_async(dispatch_get_main_queue(), ^{

            [self.collectionView reloadData];

        });
        

        if (self.callBack) {
            self.callBack(self.imgArray);
        }
        
        [self.hud dismiss:YES];
        
        } option:uploadOption];
}





@end
